package org.byqh.dqeai.util;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 文件与base64的互相转换操作
 */
public class Base64Util {
    public static String encode(byte[] ary) {
        Base64.Encoder encoder = Base64.getMimeEncoder();
        return encoder.encodeToString(ary);
    }

    public static byte[] decode(String str) {
        Base64.Decoder dec = Base64.getMimeDecoder();
        return dec.decode(str.getBytes(StandardCharsets.UTF_8));
    }

    public static String getMD5(byte[] source) {
        StringBuilder sb = new StringBuilder();
        java.security.MessageDigest md5 = null;
        try {
            md5 = java.security.MessageDigest.getInstance("MD5");
            md5.update(source);
        } catch (NoSuchAlgorithmException e) {
        }
        if (md5 != null) {
            for (byte b : md5.digest()) {
                sb.append(String.format("%02X", b));
            }
        }
        return sb.toString();
    }
}